package org.jeecg.modules.system.listener;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.golf.user.entity.Trainee;
import org.jeecg.modules.golf.user.event.TraineeEvent;
import org.jeecg.modules.golf.user.service.ITraineeService;
import org.jeecg.modules.golf.user.vo.TraineeDTO;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author jiguansheng
 * @date 2020/11/1
 * 学员管理
 **/
@Service
@Slf4j
public class TraineeListener implements ApplicationListener<TraineeEvent> {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITraineeService traineeService;



    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onApplicationEvent(TraineeEvent event) {
       TraineeDTO traineeDTO = (TraineeDTO) event.getSource();
       Trainee trainee = new Trainee();
        BeanUtil.copyProperties(traineeDTO,trainee);
       switch (event.getOperateType()){
           //新增
           case  1:
               saveUser(traineeDTO);
               trainee.setUserId(traineeDTO.getUserId());
               saveTrainee(trainee);
               break;
           //更新
           case 2:
               updateUser(traineeDTO);
               traineeService.updateById(trainee);
               break;
           default:

       }

    }

    /**
     * 学员保存
     * @param trainee
     */
    private  void saveUser(TraineeDTO trainee ){
        try {
            SysUser user = new SysUser(trainee);

            sysUserService.addUserWithRole(user, Trainee.TRAINEE_ROLE);
            sysUserService.addUserWithDepart(user, Trainee.TRAINEE_DEPART);
            trainee.setUserId(user.getId());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private  void saveTrainee(Trainee trainee){
         traineeService.save(trainee);
    }

    private void updateUser(TraineeDTO trainee){
        SysUser user =  new SysUser();
        user.updateUserByTrainee(trainee);
        sysUserService.updateById(user);
    }




}
